import {login, logout, userInfo} from '@/api';
import {getTokenHead, getTokenValue, removeToken, setTokenHead, setTokenValue} from '@/utils/token';

// 存储数据
const state = {
  tokenHead: getTokenHead(),
  tokenValue: getTokenValue(),
  userInfo: {}
}
// 操作数据
const mutations = {
  TOKEN_HEAD(state, tokenHead) {
    state.tokenHead = tokenHead;
  },
  TOKEN_VALUE(state, tokenValue) {
    state.tokenValue = tokenValue;
  },
  USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  CLEAR(state) { // 清除本地数据
    state.tokenHead = '';
    state.tokenValue = '';
    state.userInfo = {};
    removeToken(); // 清空本地存储数据
  }
}
// 响应组件中的动作，action 里面不能操作 state，提交 mutation 修改 state
const actions = {
  async login({commit}, data) {
    let result = await login(data);
    commit('TOKEN_HEAD', result.data.tokenHead);
    commit('TOKEN_VALUE', result.data.tokenValue);
    commit("USER_INFO", result.data.authentication);
    setTokenHead(result.data.tokenHead);
    setTokenValue(result.data.tokenValue); // 持久化存储 token
    return 'ok';
  },
  async userInfo({commit}) {
    let result = await userInfo();
    commit("USER_INFO", result.data);
    return 'ok';
  },
  async logout({commit}) {
    await logout();
    commit("CLEAR");
    return 'ok';
  }
}
// 获取数据
const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}
